#include "ThreadPool.hpp"
#include "Route.hpp"
#include "ChatServer.hpp"
#include <iostream>
#include <memory>

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " localport" << std::endl;
}

// // for debug
// void chat(int sockfd, std::string message, InetAddr addr)
// {
//     LOG(LogLevel::DEBUG) << "sockfd: " << sockfd;
//     LOG(LogLevel::DEBUG) << "message: " << message;
//     LOG(LogLevel::DEBUG) << "client info: " << addr.ToString();
//     sendto(sockfd, message.c_str(), message.size(), 0, addr.Addr(), addr.Length());
// }

using task_t = std::function<void()>;

// ./udp_server serverport
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    EnableConsoleLogStrategy();
    uint16_t port = std::stoi(argv[1]);

    // 1. 消息转发功能
    std::unique_ptr<Route> r = std::make_unique<Route>();

    // 2. 线程池对象
    auto tp = ThreadPool<task_t>::GetInstance();

    // 3. 服务器对象
    std::unique_ptr<ChatServer> usvr = std::make_unique<ChatServer>(port,
       [&r, &tp](int sockfd, std::string message, InetAddr addr){
            task_t task = std::bind(&Route::RouteMessageToAll, r.get(), sockfd, message, addr);
            //调用时等效于(r.get())->RouteMessageToAll(sockfd, message, addr);
            tp->Enqueue(task);
       }
    );
    usvr->Init();
    usvr->Start();

    return 0;
}